/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.sales.hancadpo.client.presenter;

import br.com.sales.generics.client.HanAbstractPresenter;
import br.com.sales.generics.client.components.autocomplete.widget.Autocomplete;
import br.com.sales.generics.client.components.mask.MaskEditHandler;
import br.com.sales.generics.client.components.scroll.HScroll;
import br.com.sales.generics.client.components.timepicker.HDateTimePicker;
import br.com.sales.generics.client.nametoken.NameTokens;
import br.com.sales.generics.client.request.HannaRequestCallback;
import br.com.sales.generics.client.utils.numbers.DecimalBox;
import br.com.sales.generics.client.presenter.events.EditRecordEvent;
import br.com.sales.generics.client.presenter.events.EditRecordHandler;
import br.com.sales.hancadpo.client.presenter.grid.HanCadPOGrid;
import br.com.sales.hancadpo.client.presenter.values.ControlValues;
import br.com.sales.hancadpo.client.service.HanCadPOService;
import com.google.gwt.core.client.JsonUtils;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.Response;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.HasUiHandlers;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.ContentSlot;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyStandard;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.gwtplatform.mvp.client.proxy.RevealContentHandler;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 *
 * @author Karine
 */
public class HanCadPOPresenter
        extends HanAbstractPresenter<HanCadPOPresenter.Display, HanCadPOPresenter.MyProxy>
        implements HanCadPOUiHanlder, EditRecordHandler {

    @ContentSlot
    public static final GwtEvent.Type<RevealContentHandler<?>> HANCADPO_SLOT_TYPE = new GwtEvent.Type<>();
    private boolean isEditing;
    @Inject
    private ControlValues controlValues;
    @Inject
    private HanCadPOService service;
    @Inject
    private HanCadPOGrid grid;
    private long sequenceEditing = 0;
    private final HTMLPanel panelGrid = new HTMLPanel("");

    @Inject
    public HanCadPOPresenter(EventBus eventBus, HanCadPOPresenter.Display view, HanCadPOPresenter.MyProxy proxy) {
        super(eventBus, view, proxy);
        getView().setUiHandlers(this);
    }

    @Override
    protected void onReveal() {
        super.onReveal();
        getView().setEnabled(isEditing);
        panelGrid.setVisible(false);
        panelGrid.add(grid);
        panelGrid.add(getView().getLoadingMessage());
        getView().getFilterContainer().setVisible(false);
        getView().setInSlot(HANCADPO_SLOT_TYPE, getView().getDetailPanel());
    }

    @Override
    protected void onBind() {
        super.onBind();
        getView().build();
        getEventBus().addHandler(EditRecordEvent.TYPE, this);
    }

    @Override
    public void onClickNew(ClickEvent event) {
        if (!isEditing) {
            setValuesRecord(true);
        } else {
            if (Window.confirm("Deseja cancelar a edição atual?")) {
                setValuesRecord(true);
            }
        }
    }

    private void setValuesRecord(boolean newRecord) {
        isEditing = true;
        getView().getFilterContainer().setVisible(false);
        getView().setEnabled(isEditing);
        getView().controlVisibleButton(isEditing);
        if (newRecord) {
            controlValues.clearFields(getView());
            setDefaultValue();
        }
        getView().getDescribeProductEdit().setFocus(true);
        if (panelGrid.isVisible()) {
            getView().setInSlot(HANCADPO_SLOT_TYPE, getView().getDetailPanel());
            panelGrid.setVisible(false);
        }
    }

    @Override
    public void onClickCancel(ClickEvent event) {
        if (Window.confirm("Deseja cancelar?")) {
            controlValues.clearFields(getView());
            isEditing = false;
            getView().setEnabled(isEditing);
            getView().controlVisibleButton(isEditing);
            grid.setIsEditing(false);
            getView().isMandatory(isEditing);
        }
    }

    @Override
    public void onClickSave(ClickEvent event) {
        if (getView().isMandatory(isEditing)) {
            return;
        } else if (!getView().getProviderEdit().isValidValue()) {
            Window.alert("Existem campos inválidos!\nFavor verificar.");
            return;
        }
        final Map params = new LinkedHashMap();
        params.put("SEQ", sequenceEditing);
        params.put("DATE", getView().getDateEdit().getText());
        params.put("PRODUCT", getView().getDescribeProductEdit().getText());
        params.put("UNIT_VALUE", getView().getValueUnitEdit().getValueUnmasked());
        params.put("BUY_VALUE", getView().getValueBuyEdit().getValueUnmasked());
        params.put("PROMOTIONAL_VALUE", getView().getValuePromotionalEdit().getValueUnmasked());
        params.put("PROFIT_MARGIN", getView().getProfitMarginEdit().getValue());
        params.put("STOCK", getView().getIsStockChec().getValue() ? "S" : "N");
        params.put("COUNT_STOCK", getView().getCountStockEdit().getValue());
        params.put("COUNT_MAX_STOCK", getView().getCountMaxStockEdit().getValue());
        params.put("COUNT_MIN_STOCK", getView().getCountMinStockEdit().getValue());
        params.put("PROVIDER_ID", getView().getProviderEdit().getValue());
        params.put("OBSERVATION", getView().getDescribeEdit().getText());

        service.insertProduct(params, new HannaRequestCallback() {

            @Override
            public void onResponseReceived(Request request, Response response) {
                JSONObject record = new JSONObject(JsonUtils.safeEval(response.getText()));
                isEditing = false;
                getView().setEnabled(isEditing);
                getView().controlVisibleButton(isEditing);
                controlValues.clearFields(getView());
                sequenceEditing = 0;
                grid.addValueTogrid(record);
            }
        });
    }

    private void setDefaultValue() {
        DateTimeFormat format = DateTimeFormat.getFormat("dd/MM/yyyy HH:mm:ss");
        getView().getDateEdit().setText(format.format(new Date(System.currentTimeMillis())));
    }

    @Override
    public void onClickGridDetail(ClickEvent event) {
        if (!panelGrid.isVisible()) {
            getView().setInSlot(HANCADPO_SLOT_TYPE, panelGrid.asWidget());
            panelGrid.setVisible(true);
            getView().getFilterContainer().setVisible(true);
            grid.update(getDataFilter());
        } else {
            getView().setInSlot(HANCADPO_SLOT_TYPE, getView().getDetailPanel().asWidget());
            panelGrid.setVisible(false);
            getView().getFilterContainer().setVisible(false);
        }
    }

    private Map getDataFilter() {
        Map param = new HashMap();
        param.put("DS_PRODUTO", getView().getFilterName().getValue());
        param.put("DT_INICIO", getView().getInitialDate().getValueAsString() + " 00:00:00");
        param.put("DT_FIM", getView().getFinalDate().getValueAsString() + " 23:59:59");

        return param;
    }

    @Override
    public void edit(JSONObject record) {
        sequenceEditing = Long.parseLong(toString(record.get("SEQ")));
        getView().getDescribeProductEdit().setText(toString(record.get("DS_PRODUTO")));
        getView().getValueUnitEdit().setValue(toString(record.get("VL_VENDA")));
        getView().getValueBuyEdit().setValue(toString(record.get("VL_COMPRA")));
        getView().getValuePromotionalEdit().setValue(toString(record.get("VL_PROMOCIONAL")));
        getView().getProfitMarginEdit().setValue(toString(record.get("PR_MARGEM_LUCRO")));
        getView().getIsStockChec().setValue(toString(record.get("IE_ESTOQUE")).equals("N"));
        getView().getCountStockEdit().setValue(toString(record.get("QT_ESTOQUE")));
        getView().getCountMaxStockEdit().setValue(toString(record.get("QT_MAX_ESTOQUE")));
        getView().getCountMinStockEdit().setValue(toString(record.get("QT_MIN_ESTOQUE")));
        getView().getProviderEdit().setValue(toString(record.get("FORNEC")), toString(record.get("NR_SEQ_PF")));
        getView().getDescribeEdit().setText(toString(record.get("DS_BREVE")));
        getView().getDateEdit().setText(toString(record.get("DT_REGISTRO")));

        setValuesRecord(false);
    }

    private String toString(JSONValue value) {
        if (value == null) {
            return "";
        }
        if (value instanceof JSONString) {
            return value.isString().stringValue();
        } else if (value instanceof JSONNumber) {
            return value.isNumber().toString();
        }
        return "";
    }

    @Override
    public void onClickRefresh(ClickEvent event) {
        grid.update(getDataFilter());
    }

    @ProxyStandard
    @NameToken(NameTokens.REGISTERSPRODUCTS)
    public interface MyProxy extends ProxyPlace<HanCadPOPresenter> {
    }

    public interface Display extends View, HasUiHandlers<HanCadPOUiHanlder> {

        HTMLPanel getContainer();

        TextBox getDescribeProductEdit();

        MaskEditHandler getValueUnitEdit();

        MaskEditHandler getValueBuyEdit();

        MaskEditHandler getValuePromotionalEdit();

        DecimalBox getProfitMarginEdit();

        DecimalBox getCountStockEdit();

        CheckBox getIsStockChec();

        DecimalBox getCountMinStockEdit();

        DecimalBox getCountMaxStockEdit();

        TextArea getDescribeEdit();

        Autocomplete getProviderEdit();

        TextBox getDateEdit();

        void build();

        boolean isMandatory(boolean isEditing);

        void setEnabled(boolean isNewrecord);

        void controlVisibleButton(boolean isNewrecord);

        HTMLPanel getDetailPanel();

        HScroll getMainContentScrollPanel();

        Image getLoadingMessage();

        HDateTimePicker getInitialDate();

        HDateTimePicker getFinalDate();

        TextBox getFilterName();

        HTMLPanel getFilterContainer();
    }
}
